/**
 * Copyright (c) 2013 Nokia Corporation. All rights reserved.
 * Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation. 
 * Oracle and Java are trademarks or registered trademarks of Oracle and/or its
 * affiliates. Other product and company names mentioned herein may be trademarks
 * or trade names of their respective owners. 
 * See LICENSE.TXT for license information.
 */

package com.nokia.example.composedui.views;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.ImageItem;
import javax.microedition.lcdui.Item;

import com.nokia.example.composedui.ViewManager;
import com.nokia.example.composedui.model.DataItem;
import com.nokia.example.composedui.model.DataItemListener;
import com.nokia.example.composedui.model.ItemStorage;
import com.nokia.example.composedui.utils.AppDataStorage;
import com.nokia.example.composedui.utils.Confirmation;
import com.nokia.example.composedui.utils.ImageUtils;
import com.nokia.example.composedui.utils.PersistableState;

/**
 * An example Form-based view, which just shows a single text line in the form
 * content area. Implements CommandLister interface to be able to detect back
 * button presses, so it can ask ViewManager to show the previous view.
 */
public class ItemView
    extends Form
    implements CommandListener,
               DataItemListener,
               PersistableState,
               ImageUtils.Listener
{
    // Members
    private final Command backCommand;
    private final Command editCommand;
    private final Command deleteCommand;
    private ViewManager viewManager;
    private DataItem dataItem;
    private ItemStorage itemStorage;
    private ImageItem imageItem;

    /**
     * Constructor.
     */
    public ItemView() {
        super(null);
        editCommand = new Command("Edit", Command.SCREEN, 1);
        deleteCommand = new Command("Delete", Command.SCREEN, 2);
        backCommand = new Command("Back", Command.BACK, 1);
        addCommand(editCommand);
        addCommand(deleteCommand);
        addCommand(backCommand);
        setCommandListener(this);
    }

    /**
     * Constructor which sets the view title, adds a back command to it and adds
     * the dummy text content to it.
     * 
     * @param viewTitle Title shown in the title bar of this view.
     * @param viewManager View manager which will handle view switching.
     */
    public ItemView(DataItem dataItem,
                    ItemStorage itemStorage,
                    ViewManager viewManager)
    {
        this();
        restoreInstance(dataItem, itemStorage, viewManager, null, null);
    }

    /**
     * @see PersistableState#restoreInstance(DataItem, ItemStorage, ViewManager, AppDataStorage, String)
     */
    public void restoreInstance(DataItem selectedDataItem,
                                ItemStorage itemStorage,
                                ViewManager viewManager,
                                AppDataStorage appDataStorage,
                                String uniqueId)
    {
        this.dataItem = selectedDataItem;
        this.dataItem.addDataItemListener(this);
        this.itemStorage = itemStorage;
        this.itemStorage.setActiveDataItem(dataItem);
        this.viewManager = viewManager;
        populateView();
    }

    /**
     * @see javax.microedition.lcdui.CommandListener#commandAction(Command, Displayable)
     */
    public void commandAction(Command command, Displayable displayable) {
        if (editCommand.equals(command)) {
            viewManager.showView(new ItemEditView(dataItem, itemStorage, viewManager));
        }
        else if (deleteCommand.equals(command)) {
            String confirmationText = "Delete " + dataItem.getName() + "?";
            Confirmation confirmation = new Confirmation(confirmationText,
                    "Delete", "Cancel", this);
            viewManager.showView(confirmation);
            
        }
        else if (Confirmation.OK_COMMAND.equals(command)) {
            dataItem.removeDataItemListener(this);
            itemStorage.removeElement(dataItem);
            itemStorage.clearActiveDataItem();
            viewManager.goBack(); // from Confirmation to this view
            viewManager.goBack(); // from this view to the listing
        }
        else if (Confirmation.CANCEL_COMMAND.equals(command)) {
            viewManager.goBack(); // from Confirmation to this view
        }
        else if (backCommand.equals(command)) {
            // Hardware back button was pressed
            dataItem.removeDataItemListener(this);
            itemStorage.clearActiveDataItem();
            viewManager.goBack();
        }
    }

    /**
     * @see DataItemListener#itemDataChanged(DataItem)
     */
    public void itemDataChanged(DataItem dataItem) {
        System.out.println("ItemView.itemDataChanged(): " + dataItem.getName());
        this.dataItem = dataItem;
        populateView();
    }

    /**
     * @see PersistableState#saveInstance(AppDataStorage, String)
     */
    public void saveInstance(AppDataStorage appDataStorage, String uniqueId) {
        // No need to do anything here
    }

    /**
     * Scales the image and creates the image item.
     * @see ImageUtils.Listener#onImageReady(Image)
     */
    public void onImageReady(int requestId, Image image) {
        final int width = getWidth();
        
        try {
            image =
                ImageUtils.pixelMixingScale(image, width,
                    image.getHeight() * width / image.getWidth());
        }
        catch (IllegalArgumentException e) {
        }
        
        if (imageItem == null) {
            imageItem = new ImageItem(null, image, Item.LAYOUT_DEFAULT, "Item image");
            append(imageItem);
        }
        else {
            imageItem.setImage(image);
        }
    }

    /**
     * @see ImageUtils.Listener#onGettingImageFailed()
     */
    public void onGettingImageFailed() {
    }

    /**
     * Updates the view based on the details of the current data item.
     */
    private void populateView() {
        deleteAll();
        imageItem = null;
        
        setTitle(dataItem.getName());
        
        Image image = ImageUtils.getImage(dataItem.getImageFileName());
        
        if (image == null) {
            ImageUtils.getImageAsync(dataItem.getImageFileName(),
                ImageUtils.DO_NOT_SCALE, ImageUtils.DO_NOT_SCALE, this);
        }
        else {
            onImageReady(0, image);
        }
    }
}
